package cn.devzyh.controller;

import cn.devzyh.domain.PromotionAdVo;
import cn.devzyh.domain.ResultVo;
import cn.devzyh.service.PromotionAdService;
import cn.devzyh.utils.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 广告模块处理器
 */
@RestController
@RequestMapping("/promotionAd")
public class PromotionAdController {

    @Autowired
    private PromotionAdService promotionAdService;

    // 广告分页查询
    @GetMapping("/findAllPromotionAdByPage")
    public ResultVo findAllPromotionAdByPage(PromotionAdVo promotionAdVo) {

        PageInfo pageInfo = promotionAdService.findAllByPage(promotionAdVo);

        return new ResultVo(true, 200, "响应成功", pageInfo);
    }

    // 图片上传
    @PostMapping("/promotionAdUpload")
    public ResultVo promotionAdUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
            throws IOException {

        if (file.isEmpty()) {
            return new ResultVo(false, 500, "上传文件不可为空", null);
        }

        String newFileName = UploadUtil.upload(file, req);
        Map<String, String> map = new HashMap<>();
        map.put("fileName", newFileName);
        map.put("filePath", "http://127.0.0.1:8080/upload/" + newFileName);
        return new ResultVo(true, 200, "上传文件成功", map);
    }

    // 新建&修改广告
    @PostMapping("/saveOrUpdatePromotionAd")
    public ResultVo saveOrUpdatePromotionAd(@RequestBody PromotionAdVo promotionAdVo) {

        ResultVo res = new ResultVo(true, 200, "", null);

        if (null == promotionAdVo.getId()) {

            promotionAdService.savePromotionAd(promotionAdVo);
            res.setMessage("广告新增成功");
        } else {

            promotionAdService.updatePromotionAd(promotionAdVo);
            res.setMessage("广告修改成功");
        }

        return res;
    }

    // 回显广告信息
    @GetMapping("/findPromotionAdById")
    public ResultVo findPromotionAdById(@RequestParam(value = "id", required = true) Integer id) {

        return new ResultVo(true, 200, "响应成功", promotionAdService.findOneById(id));
    }

    // 广告状态上下线
    @GetMapping("/updatePromotionAdStatus")
    public ResultVo updatePromotionAdStatus(@RequestParam(value = "id", required = true) Integer id,
                                            @RequestParam(value = "status", required = true) Integer status) {

        promotionAdService.updatePromotionAdStatus(id, status);
        Map map = new HashMap();
        map.put("status", status);

        return new ResultVo(true, 200, "广告状态修改成功", map);
    }
}
